#!/usr/bin/env python
# coding=utf-8

#__author__:  Administrator
#__date__:  2017/9/25

from config import settings
import os,json
# import sys

# def cmdArg():
    # attr=sys.argv[1]
    # return attr

def run():
    # attr = cmdArg()
    attr = input('读或写[r/w]——退出[q]?')
    if attr == 'q':
        exit()
    if attr == 'r':
        readFile()
    if attr == 'w':
        name = input('your name:')
        pwd = input('your password:')
        pwdData = {}
        pwdData[name] = pwd
        status = writeFile(name,pwdData)
        if not status:
            print('保存失败')
        else:
            print('保存成功')

def writeFile(file,data):
    # form = '.txt'
    target = os.path.join(settings.DbPath, file)
    try:
        with open(target,'w') as f:
            json.dump(data,f)
        return True
    except IOError as e:
        return False
    except Exception as e:
        print(e)

def readFile():
    print(os.listdir(settings.DbPath))
    fileList = os.listdir(settings.DbPath)
    selecting = input('想打开第几个...[q]退出')
    if selecting == 'q':
        exit()
    if selecting in range(len(fileList)):
        selected = int(selecting) - 1
        target = os.path.join(settings.DbPath,fileList[selected])

        try:
            with open(target,'r') as f:
                text = json.load(f)
                print(text)
            return True
        except IOError as e:
            return False
        except Exception as e:
            print(e)
    else:
        print('文件不存在')